<?php

namespace app\api\controller;

use app\admin\model\Classes;
use app\admin\model\Grade;
use app\admin\model\Personnel;
use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Session;
use app\admin\model\School as SchoolModel;

/**
 * 学校管理接口
 */
class School extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public $app;
	//$this->api = Api::instance();
   /*
	   注释人:gzy 时间 2018年8月12日 09:15:00
	   public $config = [
			'corp_id' => 'wxa8333bbf9962d0e0',//企业ID
			'agent_id' => '1000002', // 如果有 agend_id 则填写
			'secret'   => 'pIDWY-STP1kC5miEEHc-OAodEcV6_dVB2suooqgCub8',//学校管理
			// 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
			'response_type' => 'array',
			'log' => [
				'level' => 'debug',//debug  info  notice  warning  error  critical  critical  alert  emergency
				'file' => __DIR__.'/log/WechatSchool.log',
			],
			'oauth' => [
				'scopes'   => 'snsapi_privateinfo',
				'callback' => 'http://oa.fc62.com/api/school/login',
			],
		];
		end
	*/

	/**
     * 公共
	 * @author gzy
	 * @date   2018年8月12日 09:15:00
     */
	public function _initialize(){

        parent::_initialize();
		//获取默认值
		$this->config = $this->getConfig($this->getDefault('School'));
	}

    /**
     * 首页
     */
    public function index()
    {
		
        if(!$user = Session::get('workWechatUser'))//判断是否登录
        {
            return redirect($this->request->domain().'/api/school/oauth');
        }
//        $user  = Session::get('workWechatUser');
//        $this->success('全部部门', ['data' => $user]);
         return redirect($this->request->domain().'/school');
    }

    /**
     * 查看学校详情
     * @param $id
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function show($id)
    {
        $this->success('查看详情',SchoolModel::find($id)->toArray());
    }


    /**
     * 添加学校信息
     * @param array  $school['name'] (name="id", type="integer", required=true, description="会员ID")
     * @param string $grade
     * @param string $lat 纬度
     */
    public function add()
    {
        $dataArray = [ ];
        //post 接收数据
        if ($this->request->isPost()) {
            $dataArray['school'] = $this->request->post("school/a");
            $dataArray['grade'] = $this->request->post("grade/a");
            $dataArray['class'] = $this->request->post("class/a");
            $dataArray['personnel'] = $this->request->post("personnel/a");
            if($this->request->post("school/a"))//学校信息
            {
                unset($dataArray['school']['school_id']);
                unset($dataArray['school']['class']);
                unset($dataArray['school']['total_number']);
                if($dataArray['school']['type'] != 1)
                {
                    unset($dataArray['school']['policylist']);
                }
                if($dataArray['school']['type'] == 3)
                {
                    unset($dataArray['school']['is_schoolsdata']);
                }
                $dataArray['school']['textbook_edition'] = json_encode(array_column($dataArray['school']['textbook_edition'], 'fraction', 'name'));
                if(!empty($dataArray['school']['bookstore']))
                {
                    $dataArray['school']['bookstore'] = serialize($dataArray['school']['bookstore']);//书店数据 序列化数据
                }
                $ModelSchool = SchoolModel::create($dataArray['school'],array_keys($dataArray['school']));
                $this->addSchool($dataArray,$ModelSchool['id']);
            }

        }
        $this->success('添加信息','success');
    }

    /**
     * 获取学校列表
     * @param int $page 翻页
     */
    public function getSchoolList($page = 1)
    {
		header('Access-Control-Allow-Credentials:true');
		if(!$user = Session::get('workWechatUser'))//判断是否登录
        {
            return 0;
        }
        $schoolList = new SchoolModel();
        $schoolList = collection($schoolList->apiSchoolList($page))->toArray();
        $this->success('学校列表', array_column($schoolList,null,'id'));
    }

    public function oauth()
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }

    public function login()
    {
        if(!$user = Session::get('workWechatUser'))
        {
            $app = Factory::work($this->config);
            $token = $app->access_token->getToken();//获取企业微信token
            $code = $this->request->request('code');
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
            $user = $this->curlLogin($url);
            $newUser = new User();
            $user  = $newUser->getUserInfo($user['UserId']);
            $department = new Department();
            $user['departmentName'] = $department->getDepartmentName($user['department']);
            Session::set('workWechatUser',$user);
        }
//        $this->success('登录成功', ['data' => $user]);
        return redirect($this->request->domain().'/api/school/index');
    }

    public function curlLogin($url)
    {
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        // 3. 执行并获取内容
        $output = curl_exec($ch);
        if($output === FALSE ){
            echo "CURL Error:".curl_error($ch);
        }
        // 4. 释放curl句柄
        curl_close($ch);
        return json_decode($output,true);
    }

    public function addSchool(array $dataArray,$school_id)
    {
        if(!empty($dataArray['grade'][0]['grade_id']))
        {
            foreach ($dataArray['grade'] as $key=>$grade)
            {
                //添加年级
                $grade['school_id'] = $school_id;
                $gradeid = $grade['grade_id'];
                unset($grade['subject']);
                unset($grade['grade_id']);
                unset($grade['total_number']);
                unset($grade['total_grade']);
                unset($grade['revision']);
                $grade['self_study'] = $grade['self_study'] ? 1 : 2 ;
                $ModelGrade = Grade::create($grade,array_keys($grade));
                if(!empty($dataArray['class'][0]['class_id']))
                {
                    foreach ($dataArray['class'] as $keyClass=>$classes)
                    {
                        if($classes['grade_id'] == $gradeid)
                        {
                            //添加班级
                            $classes['school_id'] = $school_id;
                            $classes['grade_id'] = $ModelGrade['id'];
                            $classId = $classes['class_id'];
                            unset($classes['class_id']);
                            $ModelClasses = Classes::create($classes,array_keys($classes));
                            if(!empty($dataArray['personnel']))
                            {
                                foreach ($dataArray['personnel'] as $keyPersonnel=>$personnel)
                                {
                                        if($personnel['class_id'] == $classId)
                                        {
                                            //添加人员
                                            $personnel['school_id'] = $school_id;
                                            $personnel['grade_id'] = $ModelGrade['id'];
                                            $personnel['classes_id'] = $ModelClasses['id'];
                                            $personnel['sexlist'] = $personnel['sex'];
                                            unset($personnel['sex']);
                                            unset($personnel['is_class']);
                                            unset($personnel['class_id']);
                                            $Model = Personnel::create($personnel,array_keys($personnel));
                                        }
                                }
                            }
                        }
                    }
                }
            }
        }
        if(!empty($dataArray['personnel'][0]['role']))
        {
            foreach ($dataArray['personnel'] as $keyPersonnel=>$personnel)
            {
                if($personnel['role'] == 1 || $personnel['role'] == 2)
                {
                    //添加校长副校长
                    $personnel['school_id'] = $school_id;
                    $personnel['sexlist'] = $personnel['sex'];
                    unset($personnel['sex']);
                    unset($personnel['is_class']);
                    unset($personnel['class_id']);
                    $Model = Personnel::create($personnel,array_keys($personnel));
                }
            }
        }
        return true;

    }

}
